import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
  Tree,
  Tooltip,
} from 'antd';
const { RangePicker } = DatePicker;
const confirm = Modal.confirm;
const { TextArea, Search } = Input;
const { TreeNode } = Tree;
import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import {
  serviceConfigList,
  serviceConfigUpdate,
  serviceConfigDelete,
  serviceConfigAdd,
} from '../../services/api';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import counties from '../../data/counties.json';

import styles from './serviceConfig.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const STATUS_ARR = [
  {
    id: 0,
    name: '停用',
  },
  {
    id: 1,
    name: '启用',
  },
];

const pageSize = 10;

@connect(({ serviceConfig, loading }) => {
  return {
    serviceConfig,
    loading: loading.models.serviceConfig,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    treeData: [],
    searchValue: '',
    dataList: [],
    showEdit: false,
  };

  componentDidMount() {
    this.init();
    this.leftRef = React.createRef();
  }

  async init() {
    const hide = message.loading('加载中', 0);
    const response = await serviceConfigList({});
    if (response.code === 200) {
      let treeData = response.data.children;
      let dataList = [];
      this.buildTreeData(treeData, dataList);
      this.setState({
        treeData: treeData,
        dataList,
      });

      setTimeout(hide, 10);
    } else {
      message.error(response.message);
    }
  }

  buildTreeData(data, dataList) {
    for (let i = 0; i < data.length; i++) {
      const _temp = data[i];
      dataList.push({ key: data[i].itemId, title: data[i].itemName, props: data[i] });
      if (data[i].children) {
        data[i].key = data[i].itemId;
        data[i].title = data[i].itemName;
        this.buildTreeData(data[i].children, dataList);
      }
    }
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'serviceConfig/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    this.init();
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        type: fieldsValue.type,
        pageNum: 1,
        pageSize: PAGE_SIZE,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'serviceConfig/queryList',
        payload: values,
      });
    });
  };

  handleShowModal = e => {
    e.preventDefault();
    this.setState({
      id: null,
      modalVisible: true,
      title: '',
      editorState: EditorState.createEmpty(),
    });
  };

  handleReset() {}

  async handleSave(e) {
    const { parentItemId, content } = this.state;

    const { form } = this.props;

    form.validateFields(async (err, fieldsValue) => {
      if (err) return;

      const values = {
        parentItemId,
        content: content.toHTML(),
        ...fieldsValue,
      };

      await this.doSave(values);
    });
  }

  async doSave(values) {
    const { dispatch } = this.props;

    const { id } = this.state;

    if (id) {
      values.itemId = id;
      const response = await serviceConfigUpdate(values);

      if (response.code === 200) {
        this.init();
        message.success('修改成功');
      } else {
        message.error(response.message);
      }
    } else {
      const response = await serviceConfigAdd(values);

      if (response.code === 200) {
        this.init();
        message.success('新增成功');
      } else {
        message.error(response.message);
      }
    }
  }

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  handleEdit(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  async handleDelete(item) {
    const { dispatch } = this.props;

    confirm({
      title: '确认删除',
      content: '是否删除？',
      onOk: (async () => {
        let { errno, errmsg, data } = await serviceConfigDelete({
          id: item.id,
        });
        if (!errno) {
          message.success('删除成功');
          this.init();
        }
      }).bind(this),
      onCancel() {},
    });
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  handleSelectOnchange(field, value) {
    this.setState({
      [field]: value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  onRadioChange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onExpand = expandedKeys => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (this.getParentKey(key, node.children)) {
          parentKey = this.getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  onChange = e => {
    const { value } = e.target;
    if (!value) {
      return false;
    }
    const { treeData } = this.state;
    const expandedKeys = this.state.dataList
      .map(item => {
        if (item.title.indexOf(value) > -1) {
          return this.getParentKey(item.key, treeData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true,
    });
  };

  onRightClick = ({ event, node }) => {
    var x = event.currentTarget.offsetLeft + event.currentTarget.clientWidth;
    var y = event.currentTarget.offsetTop;
    this.setState(
      {
        NodeTreeItem: {
          pageX: x,
          pageY: y,
          id: node.props.eventKey,
          isLeaf: !node.props.children || !node.props.children.length,
        },
      },
      () => {
        setTimeout(() => {
          let leftRef = this.refs.leftRef;
          leftRef.scrollLeft = 200;
        }, 500);
      }
    );
  };

  handleAddService() {
    this.setState({
      showEdit: true,
      id: null,
      parentItemId: this.state.NodeTreeItem.id,
      content: null,
    });
    this.props.form.setFieldsValue({
      itemName: '',
      itemValue: '',
      itemStatus: 1,
      pcTitle: '',
      pcKeywords: '',
      pcDesc: '',
      mobileTitle: '',
      mobileKeywords: '',
      mobileDesc: '',
      content: '',
    });
  }

  handleEditService() {
    const { dataList, treeData, NodeTreeItem } = this.state;

    const data = dataList.find(item => item.key === parseInt(NodeTreeItem.id)).props;

    this.props.form.setFieldsValue({
      itemName: data.itemName,
      itemValue: data.itemValue,
      itemStatus: data.itemStatus,
      pcTitle: data.pcTitle,
      pcKeywords: data.pcKeywords,
      pcDesc: data.pcDesc,
      mobileTitle: data.mobileTitle,
      mobileKeywords: data.mobileKeywords,
      mobileDesc: data.mobileDesc,
    });

    const parentItemId = this.getParentKey(parseInt(NodeTreeItem.id), treeData);
    const content = BraftEditor.createEditorState(data.content);
    this.setState({
      showEdit: true,
      id: NodeTreeItem.id,
      parentItemId,
      content,
    });
  }

  handleDelService() {
    const { dataList, treeData, NodeTreeItem } = this.state;

    confirm({
      title: '确认删除',
      content: '是否删除？',
      onOk: (async () => {
        let { errno, errmsg, data } = await serviceConfigDelete({
          id: NodeTreeItem.id,
        });
        if (!errno) {
          message.success('删除成功');
          this.init();
        }
      }).bind(this),
      onCancel() {},
    });
  }

  getNodeTreeMenu() {
    const { pageX, pageY } = { ...this.state.NodeTreeItem };
    const tmpStyle = {
      position: 'absolute',
      maxHeight: 40,
      textAlign: 'center',
      left: `${pageX + 10}px`,
      top: `${pageY}px`,
      display: 'flex',
      flexDirection: 'row',
      zIndex: 999,
    };
    const menu = (
      <div style={tmpStyle}>
        {!this.state.NodeTreeItem.isLeaf && (
          <div
            style={{ alignSelf: 'center', marginLeft: 10 }}
            onClick={this.handleAddService.bind(this)}
          >
            <Tooltip placement="bottom" title="新增">
              <Icon type="plus-circle-o" />
            </Tooltip>
          </div>
        )}
        {this.state.NodeTreeItem.isLeaf && (
          <div
            style={{ alignSelf: 'center', marginLeft: 10 }}
            onClick={this.handleEditService.bind(this)}
          >
            <Tooltip placement="bottom" title="修改">
              <Icon type="edit" />
            </Tooltip>
          </div>
        )}
        {this.state.NodeTreeItem.isLeaf && (
          <div
            style={{ alignSelf: 'center', marginLeft: 10 }}
            onClick={this.handleDelService.bind(this)}
          >
            <Tooltip placement="bottom" title="删除">
              <Icon type="minus-circle-o" />
            </Tooltip>
          </div>
        )}
      </div>
    );
    return this.state.NodeTreeItem == null ? '' : menu;
  }

  clearMenu = () => {
    this.setState({
      NodeTreeItem: null,
    });
  };

  handleEditorChange = editorState => {
    this.setState({
      content: editorState,
    });
  };

  renderEditForm() {
    const { getFieldDecorator } = this.props.form;
    const { parentItemId, dataList } = this.state;

    let parentItemName = '';
    if (parentItemId) {
      parentItemName = dataList.find(item => item.key === parseInt(parentItemId)).title;
    }

    return (
      <Form onSubmit={this.handleSave.bind(this)} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 24 }}>
          <Col md={12} sm={24}>
            <FormItem label="所在目录">
              <Input placeholder="" disabled={true} value={parentItemName} />
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem label="服务名称">
              {getFieldDecorator('itemName')(<Input placeholder="" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 24 }}>
          <Col md={12} sm={24}>
            <FormItem label="服务价格">
              {getFieldDecorator('itemValue')(<Input placeholder="" />)}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem label="服务状态">
              {getFieldDecorator('itemStatus')(
                <Select style={{ width: 172 }} placeholder="">
                  {STATUS_ARR.map(item => {
                    return (
                      <Option key={item.id} value={item.id}>
                        {item.name}
                      </Option>
                    );
                  })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Divider />
        <Row gutter={{ md: 8, lg: 24, xl: 24 }}>
          <Row gutter={{ md: 8, lg: 24, xl: 24 }}>
            <Col md={12} sm={24}>
              <DescriptionList size="large" title="PC 端" col="1">
                <Description>
                  <FormItem label="Title">
                    {getFieldDecorator('pcTitle')(<Input placeholder="" />)}
                  </FormItem>
                </Description>
                <Description>
                  <FormItem label="Keywords">
                    {getFieldDecorator('pcKeywords')(<Input placeholder="" />)}
                  </FormItem>
                </Description>
                <Description>
                  <FormItem label="Description">
                    {getFieldDecorator('pcDesc')(<Input placeholder="" />)}
                  </FormItem>
                </Description>
              </DescriptionList>
            </Col>
            <Col md={12} sm={24}>
              <DescriptionList size="large" title="移动端" col="1">
                <Description>
                  <FormItem label="Title">
                    {getFieldDecorator('mobileTitle')(<Input placeholder="" />)}
                  </FormItem>
                </Description>
                <Description>
                  <FormItem label="Keywords">
                    {getFieldDecorator('mobileKeywords')(<Input placeholder="" />)}
                  </FormItem>
                </Description>
                <Description>
                  <FormItem label="Description">
                    {getFieldDecorator('mobileDesc')(<Input placeholder="" />)}
                  </FormItem>
                </Description>
              </DescriptionList>
            </Col>
          </Row>
        </Row>
        <Divider />
        <Row gutter={{ md: 8, lg: 24, xl: 24 }}>
          <Col md={24} sm={24}>
            <DescriptionList style={{ width: '100%' }} size="large" title="服务详情" col="1">
              <div style={{ border: '1px solid #ccc' }}>
                <BraftEditor
                  value={this.state.content}
                  onChange={this.handleEditorChange.bind(this)}
                />
              </div>
            </DescriptionList>
          </Col>

          <Col md={24} sm={24}>
            <div style={{ flex: 1, textAlign: 'center', marginTop: 30 }}>
              <Button type="primary" onClick={this.handleSave.bind(this)}>
                保存
              </Button>
              &nbsp;&nbsp;
              <Button type="primary" onClick={this.handleReset.bind(this)}>
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    let { serviceConfig: { data }, loading } = this.props;
    const {
      selectedRows,
      modalVisible,
      expandedKeys,
      autoExpandParent,
      treeData,
      searchValue,
      showEdit,
    } = this.state;

    const columns = [
      {
        title: '站点类型',
        dataIndex: 'site',
        render: (val, item) => <span>{val === 0 ? 'WEB端' : '移动端'}</span>,
      },
      {
        title: '页面',
        dataIndex: 'type',
        render: (val, item) => <span>{PAGE_MAP[val]}</span>,
      },
      {
        title: 'Title',
        dataIndex: 'title',
      },
      {
        title: 'Keywords',
        dataIndex: 'keywords',
      },
      {
        title: 'Description',
        dataIndex: 'description',
      },
      {
        title: '操作',
        dataIndex: '',
        render: (val, item) => (
          <span>
            <a href="javascript:;" onClick={this.handleEdit.bind(this, item)}>
              编辑
            </a>&nbsp;
            <a onClick={this.handleDelete.bind(this, item)}>删除</a>
          </span>
        ),
      },
    ];

    const loop = data =>
      data.map(item => {
        const index = item.title.indexOf(searchValue);
        const beforeStr = item.title.substr(0, index);
        const afterStr = item.title.substr(index + searchValue.length);
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span style={{ color: '#f50' }}>{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{item.title}</span>
          );
        if (item.children) {
          return (
            <TreeNode key={item.key} title={title}>
              {loop(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode key={item.key} title={title} />;
      });

    return (
      <PageHeaderLayout title="服务配置">
        <Card bordered={false}>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={6} sm={24} style={{ borderRight: '1px solid #ccc', minHeight: 200 }}>
              <div
                ref={'leftRef'}
                style={{ position: 'relative', width: '100%', overflow: 'auto' }}
              >
                <Search
                  style={{ marginBottom: 8 }}
                  placeholder="Search"
                  onChange={this.onChange.bind(this)}
                />
                <Tree
                  onRightClick={this.onRightClick.bind(this)}
                  onExpand={this.onExpand.bind(this)}
                  expandedKeys={expandedKeys}
                  autoExpandParent={autoExpandParent}
                >
                  {loop(treeData)}
                </Tree>
                {this.state.NodeTreeItem != null ? this.getNodeTreeMenu() : ''}
              </div>
            </Col>
            <Col md={18} sm={24}>
              {this.renderEditForm()}
            </Col>
          </Row>
        </Card>
      </PageHeaderLayout>
    );
  }
}
